import random
from threading import Lock
from app import socketio
import json
thread = None
thread_lock = Lock()




@socketio.on('connect')
def test_connect():
    """
    定时推送数据
    :return:
    """
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)


def background_thread():
    """
    后台线程
    :return:
    """
    while True:
        socketio.sleep(10)
        t = random.randint(1, 100)
        socketio.emit('server_response',
                      test_data())


def test_data():
    tdata = {f"tdata{i}":[random.randint(0,100) for _ in range(6)] for i in range(1,7)}
    return json.dumps(tdata)
